"""
@release: fsray-api-alpha
@file: role.py
@author: lingdubing
@desc: 操作角色行为的接口层
@character: utf-8
"""


from core.Auth import check_permission
from fastapi import APIRouter, Depends
from models.models import Role, Access, RoleAccessLink
from schemas.response import *
from sqlmodel import Session, select
from database.mysql import engine
from service.RoleService import RoleService
from service.AccessService import AccessService
from service.RoleAccessService import RoleAccessService
from schemas.role_schemas import *


router = APIRouter()


@router.post('/get_role_list', summary='获得角色列表', response_model=ReturnDataModel,
            dependencies=[Depends(check_permission)])
async def get_role_list(query: RolePaingtionModel):
    """
    获得角色列表
    :param query:
    :return:
    """

    role_list = []
    role_service = RoleService()
    role_list, total = role_service.get_paginated(page=query.page, page_size=query.page_size)

    final_list = []

    if total <= 0:
        role_service.close()
        return ReturnDataModel(code=STATUS_CODE["error"], message="查询失败,出现异常", success=False, data=[], total=0)
    else:
        for val in role_list:
            role_dict = {
                'create_time': val.create_time,
                'role_id': val.role_id,
                'role_name': val.role_name,
                'role_desc': val.role_desc,
            }
            final_list.append(role_dict)
        role_service.close()
        return ReturnDataModel(code=STATUS_CODE["success"], message="查询成功", success=True, data=final_list, total=total)

@router.get('/get_role_menu_access', summary="获得角色需要验证的菜单权限")
async def get_role_menu_access(role_id: int):
    """
    获得角色需要验证的菜单权限
    :param role_id:
    :return:
    """

    role_service = RoleService()
    access_service = AccessService()
    role_access_service = RoleAccessService()

    role_info = role_service.get_role_by_role_id(role_id)

    if role_info is None:
        role_service.close()
        return ReturnDataModel(code=STATUS_CODE["error"], message="查询失败,角色id不存在", success=False, data=[],
                               total=0)

    verify_menu_access = access_service.get_verify_access()
    verify_menu_access_list = []
    role_access_list = []
    for val in verify_menu_access:
        access_info = {
            'access_id': val.access_id,
            'access_name': val.access_name,
            'use': False
        }
        verify_menu_access_list.append(access_info)
    role_access_link = role_access_service.get_access_by_role(role_id)
    for val in role_access_link:
        role_access_list.append(val.access_id)
    for val in verify_menu_access_list:
        if val['access_id'] in role_access_list:
            val['use'] = True
    return ReturnDataModel(code=STATUS_CODE["success"], message="查询成功", success=True, data=verify_menu_access_list,
                       total=len(verify_menu_access_list))




